<!--
* description: 供应商发货单管理
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      v-if="initTemplate"
      ref="multipleTable"
      :dynamicButtons="tableButtons"
      :dynamicComponents="tableComponents"
      :dynamicApiConfig="apiConfig"
      :dynamicTableCols="tableCols"
      :dynamicFormFields="formField"
      :dynamicUnFormFields="unFormField"
      :dynamicIsShowSelect="true"
      :dynamicIsColumnDrop="true"
      :callbackObj="callbackObj"
    >
      <template slot="controlBtn" slot-scope="scope">
        <el-link
          type="primary"
          class="el-icon-document"
          :underline="false"
          @click="detail(scope.row)"
          title="明细"
          style="font-size: 12px"
          >明细</el-link
        >
      </template>
      <template slot="PURCHASE_CODE" slot-scope="scope">
        <el-link
          type="primary"
          class="el-icon-edit"
          :underline="false"
          @click="edit(scope.row.index)"
          :title="scope.row.PURCHASE_CODE"
          style="font-size: 12px"
          >{{ scope.row.PURCHASE_CODE }}</el-link
        >
      </template>
    </one-table-template>
    <edit
      :dynamicEditRowData="editRowData"
      :popupsVisible="editPopupsVisible"
      :key="editPopupsKey"
      :popupsState="editPopupsState"
      @close="close"
    />
    <detail
      v-if="isShow"
      :rowData="rowData"
      @detailClose="detailClose"
      :isShow="isShow"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import { wmsApis } from "@/api/wms/purchase/api";
import OneTableTemplate from "@/components/wms/templates/oneTable";
import request from "@/utils/request";
import store from "@/store";
export default {
  name: "purchaseOrderMake",
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],
  components: {
    OneTableTemplate,
    Edit: () => import("./edit"),
    detail: () => import("./detail"),
  },
  watch: {
    $route(val) {
      if (
        this.formField.pageId !== "" &&
        this.$route.query.pageId !== undefined &&
        this.$route.query.pageId !== this.formField.pageId
      ) {
        this.formField.pageId = this.$route.query.pageId;
        this.formField.pageName = this.$route.query.pageName;
        this.queryTable();
      }
    },
  },
  created() {
    if (this.$route.query != null) {
      // 判断传入query参数，初始化数据
      if (this.$route.query.pageId != null && this.$route.query.pageId !== "") {
        this.formField.pageId = this.$route.query.pageId;
        this.formField.pageName = this.$route.query.pageName;
      }
    }
  },
  mounted() {
    this.querySelect();      
  },
  data() {
    
    return {
         partNoBefore:'', //备件编号  处理前不加逗号的
      // 网格查询API配置对象
      apiConfig: wmsApis.queryPurchaseM,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          clickEvent: () => this.queryTable(),
          name: "search",
          position: "right",
          text: "查询", //"查询"
        },
        // {
        //   compKey: "btnKey2",
        //   type: "",
        //   size: "small",
        //   clickEvent: () => this.add(),
        //   name: "add",
        //   position: "left",
        //   text: "新增",
        // },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          name: "reset",
          position: "right",
          clickEvent: () => this.reset(),
          text: "重置",
        },
         {
          compKey: "btnKey6",
          type: "",
          size: "small",
          clickEvent: () => this.export(),
          name: "export",
          position: "left",
          text: "导出", //"导出"
        },
        // {
        //   compKey: "btnKey4",
        //   type: "",
        //   size: "small",
        //   clickEvent: () => this.delete(),
        //   name: "deleteSheet",
        //   position: "left",
        //   text: "结案",
        // },
        // {
        //   compKey: "btnKey5",
        //   type: "",
        //   size: "small",
        //   clickEvent: () => this.submissionUp(),
        //   name: "submissionUp",
        //   position: "left",
        //   text: "提交",
        // },
        // {
        //   compKey: "btnKey6",
        //   type: "",
        //   size: "small",
        //   name: "importTemplateDownload",
        //   position: "left",
        //   clickEvent: () => this.downloadTemplate(),
        //   text: "模板下载",
        // },
        // {
        //   compKey: "btnKey7",
        //   text: "导入",
        //   category: "ve",
        //   codeField: "fileChannel",
        //   position: "upload",
        //   isMust: true,
        // },
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "compKey1",
          labelName: "到货仓库",
          codeField: "WAREHOUSE_IDS",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          isMul: true,
          options: [],
        },
        {
          compKey: "compKey2",
          labelName: "供应商编号",
          codeField: "SUPPLIER_CODE",
          component: () => import("@/components/wms/commonInput"),
          type: "inputText",
          isMust: true,
        },
        {
          compKey: "compKey3",
          labelName: "备件编号",
          codeField: "PART_NOS_NEW", //['0','9]
          component: () => import("@/components/org/commonInput/textareaInput"),
          // type: "inputText",
          isMust: true,
        },
        {
          compKey: "compKey4",
          labelName: "采购类型",
          codeField: "PURCHASE_TYPE",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          isMul: false,
          options: [],
        },
        {
          compKey: "compKey5",
          labelName: "采购单号",
          codeField: "PURCHASE_CODE",
          component: () => import("@/components/wms/commonInput"),
          type: "inputText",
          isMust: true,
        },
        // {
        //   compKey: "compKey6",
        //   labelName: "审核状态",
        //   codeField: "AUDIT_STATUS",
        //   component: () => import("@/components/wms/dropdownList/dropdownList"),
        //   type: "dropdownList",
        //   isMust: true,
        //   isMul: false,
        //   options: [],
        // },
        {
          compKey: "compKey7",
          labelName: "要求到货时间",
          codeField: "RA_TIME_START",
          component: () => import("@/components/wms/datePicker/andtDatePicker"),
          type: "date",
          isMust: true,
        },
        {
          compKey: "compKey8",
          labelName: "订单创建时间",
          codeField: "CREATED_DATE_START",
          component: () => import("@/components/wms/datePicker/andtDatePicker"),
          type: "date",
          isMust: true,
        },
        // {
        //   compKey: "compKey9",
        //   labelName: "状态",
        //   codeField: "IS_ENABLE",
        //   component: () => import("@/components/wms/dropdownList/dropdownList"),
        //   type: "dropdownList",
        //   isMust: true,
        //   isMul: false,
        //   options: [
        //     {
        //       label: "启用",
        //       value: "1",
        //     },
        //     {
        //       label: "作废",
        //       value: "0",
        //     },
        //   ],
        // },
      ],
      // 动态生成网格列
      tableCols: [
        // {
        //   prop: "controlBtn",
        //   label: "操作", //"操作"
        //   codeField: "controlBtn",
        //   width: 80,
        //   align: "center",
        //   isSlot: true,
        // },
        {
          prop: "PURCHASE_CODE",
          label: "采购单号",
          align: "center",
          isSlot: true,
        },
        {
          prop: "SUPPLIER_CODE",
          label: "供应商编号",
          align: "center",
        },
        {
          prop: "PARTNER_SHORT_NAME",
          label: "供应商简称",
          align: "center",
        },
        {
          prop: "PURCHASE_TYPE_NAME",
          label: "采购类型",
          align: "center",
        },
        
          
        
        {
          prop: "WAREHOUSE_NAME",
          label: "到货仓库",
          align: "center",
        },
        //  {
        //   prop: "IS_ENABLE_STR",
        //   label: "状态",
        //   align: "center",
        // },
        {
          prop: "RA_TIME_NEW",
          label: "到货要求时间",
          align: "center",
        },
       

        {
          prop: "CREATED_DATE_NEW",
          label: "订单创建时间",
          align: "center",
        },
        // {
        //   prop: "AUDIT_STATUS_NAME",
        //   label: "审核状态",
        //   align: "center",
        // },
        {
          prop: "REMARK",
          label: "备注",
          align: "center",
        },
      ],
      //表单查询数据
      formField: {
        WAREHOUSE_IDS: "",
        SUPPLIER_CODE: "",
        PART_NO: "",
        PURCHASE_TYPE: "",
        PURCHASE_CODE: "",
        AUDIT_STATUS: "",
        RA_TIME_START:"",
        WAREHOUSE_IDS_NEW: "",
        CREATED_DATE_START :"",
        IS_ENABLE:"",
        PURCHASE_TYPE:"",
        AUDIT_STATUS:"",
        WAREHOUSE_ID:"",
        ARRIVAL_QTY : "",
        PART_NOS_NEW:"",     
        ORDER_STATUS :"06"

      
      },
      unFormField: {},

      // 控制明细弹窗
      isShow: false,
      // 行数据
      rowData: {},
      // 回调函数
      callbackObj: {
        //  当选择项发生变化时会触发该事件
        onCheckSelectChange: (selection) => {
          this.checkTableList = selection;
        },
      },
              callbackObj: {
        onBeforeQuery: queryObj => {
          queryObj.variables.PART_NOS_NEW = queryObj.variables.PART_NOS_NEW.trim()
            .split("\n")
            .toString();
        
        }
      },

      // 选中的表格数据
      checkTableList: [],
      // 控制初始化页面
      initTemplate: false,
    };
  },
  methods: {
    submissionUp() {
      if (this.checkTableList.length > 0) {
        this.$confirm("确定要提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(() => {
            request({
              url: "/mp/wm/vl/warehouse/purchase/purchaseSubmit.do",
              method: "post",
              data: {
                Submit: this.checkTableList,
              },
            }).then((res) => {
              if (res.result === "1") {
                this.queryTable();
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: res.debugMsg ? res.debugMsg : res.msg,
                  type: "warn",
                });
              }
            });
          })
          .catch((err) => {
            console.info(err);
          });
      } else {
        this.$message({
          message: "请选择一条数据",
        });
      }
    },
    delete() {
      if (this.checkTableList.length > 0) {
        this.$confirm("确定要结案吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(() => {
            request({
              url: "/mp/wm/vl/warehouse/purchase/purchaseCloseCase.do",
              method: "post",
              data: {
                CloseCase: this.checkTableList,
              },
            }).then((res) => {
              if (res.result === "1") {
                this.queryTable();
                this.$message({
                  message: "结案成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: res.debugMsg ? res.debugMsg : res.msg,
                  type: "warn",
                });
              }
            });
          })
          .catch((err) => {
            console.info(err);
          });
      } else {
        this.$message({
          message: "请选择一条数据",
        });
      }
    },
    detail(row) {
      this.rowData = row;
      this.isShow = true;
    },
    detailClose() {
      this.isShow = false;
    },
    querySelect() {
      // 加载遮罩  暂不使用
      store.dispatch("app/loading", true);
      request({
        url: "/mp/wm/vl/basedata/warehouseuser/queryUserByWHBox.do",
        method: "post",
        data: {
          IS_ENABLE: "1",
        },
      }).then((res) => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map((item) => {
            this.formField.WAREHOUSE_IDS_NEW += item.WAREHOUSE_ID + ",";
            this.tableComponents[0].options.push({
              label: item.WAREHOUSE_NAME,
              value: item.WAREHOUSE_ID,
            });
          });
          this.formField.WAREHOUSE_IDS_NEW =
            this.formField.WAREHOUSE_IDS_NEW.substr(
              0,
              this.formField.WAREHOUSE_IDS_NEW.length - 1
            );
          this.formField.WAREHOUSE_IDS = res.listRow[0].WAREHOUSE_ID;
        }
        this.initTemplate = true;
        this.$nextTick(() => {
          this.queryTable();
        });
      });
      request({
        url: "/mp/wm/vl/warehouse/purchase/queryPurchaseTypeBox.do",
        method: "post",
        data: {},
      }).then((res) => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map((item) => {
            if (item.PURCHASE_TYPE != "03") {
              this.tableComponents[3].options.push({
                label: item.PURCHASE_TYPE_NAME,
                value: item.PURCHASE_TYPE,
              });
            }
          });
        }
      });
      request({
        url: "/mp/wm/vl/warehouse/purchase/queryPurchaseAuditStatusBox.do",
        method: "post",
        data: {},
      }).then((res) => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map((item) => {
            if (
              item.AUDIT_STATUS === "05" ||
              item.RA_TIME_START === "30" ||
              item.RA_TIME_START !== "40"
            ) {
              this.tableComponents[5].options.push({
                label: item.AUDIT_STATUS_NAME,
                value: item.AUDIT_STATUS,
              });
            }
          });
        }
      });
    },
    downloadTemplate() {
      let downloadElement = document.createElement("a");
      let href = "/wms/fileTemplate/采购单制作导入模板.xlsx"; // 创建下载的链接
      downloadElement.href = href;
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handFileListChange(file, fileList) {},
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过50M",
          type: "warning",
        });
        return false;
      }
      let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message({
          message: "只能导入后缀为xls,xlsx的文件！",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: "导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const that = this;
      const url = "/mp/wm/vl/warehouse/purchase/importExcelToPurchase.do";
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close();
          if (response.result === "1") {
            this.$message({
              message: "导入成功",
              type: "success",
            });
            that.queryTable();
          } else {
            this.$message({
              message: response.msg,
              type: "warning",
            });
          }
        })
        .catch((err) => {});
    },
      export() {
        this.partNoBefore = this.formField.PART_NOS_NEW;
     
      this.formField.PART_NOS_NEW = this.formField.PART_NOS_NEW.trim().split("\n").toString();
  
      const exportLoading = this.$loading({
        lock: true,
        text: "正在导出...",
        // spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        fullscreen: true,
      });
      request({
        url: "/mp/wm/vl/warehouse/ManagementPurchase/exportArrivalD.do",
        method: "post",
        headers: {
          "Cache-Control": "no-cache, no-store,max-age=0, must-revalidate",
          Pragma: "no-cache",
          Expires: "0",
          "Content-Type": "application/json;charset=UTF-8",
        },
        responseType: "blob",
        data: this.formField,
      })
        .then((response) => {
          exportLoading.close();
          let blob = new Blob([response], { type: "application/vnd.ms-excel" }); // 这里表示xmlx类型
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "供应商发货单导出.xls"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        })
         .then(response =>{
        this.formField.PART_NOS_NEW = this.partNoBefore;
        })
        .catch((err) => {
          exportLoading.close();
          console.log(err);
        });
    },
  }
  
};
</script>
